package com.mmx.baseservice.common.wechat.ma.controller;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import cn.binarywang.wx.miniapp.bean.WxMaPhoneNumberInfo;
import cn.binarywang.wx.miniapp.bean.WxMaUserInfo;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.mmx.baseservice.common.ex.ServiceException;
import com.mmx.baseservice.common.utils.CommUtil;
import com.mmx.baseservice.common.utils.LogUtil;
import com.mmx.baseservice.common.utils.returnbody.ResultCodeInfo;
import com.mmx.baseservice.common.utils.returnbody.ReturnBody;
import com.mmx.baseservice.user.pojo.UsInfo;
import com.mmx.baseservice.user.service.UsInfoService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import me.chanjar.weixin.common.error.WxErrorException;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * 微信小程序用户接口
 *
 * @author <a href="https://github.com/binarywang">Binary Wang</a>
 */
@Api(tags = "微信小程序 - 用户接口")
@RestController
@RequestMapping("/wx/ma/user")
public class WxMaUserController {

    @Resource
    private WxMaService wxMaService;
    @Resource
    private HttpServletRequest request;
    @Resource
    private UsInfoService usInfoService;

    @ApiOperation("授权登录")
    @GetMapping("/login")
    public String login(String code) {
        if (StringUtils.isBlank(code)) {
            return "empty jscode";
        }
        try {
            WxMaJscode2SessionResult session = wxMaService.getUserService().getSessionInfo(code);
            LogUtil.info(session.getSessionKey());
            LogUtil.info(session.getOpenid());
            //TODO 可以增加自己的逻辑，关联业务相关数据
            return JSONObject.toJSONString(session);
        } catch (WxErrorException e) {
            LogUtil.error(e.getMessage(), e);
            return e.toString();
        }
    }

    /**
     * <pre>
     * 获取用户信息接口
     * </pre>
     */
    @GetMapping("/info")
    public String info(String sessionKey,String signature, String rawData, String encryptedData, String iv) {
        // 用户信息校验
        if (!wxMaService.getUserService().checkUserInfo(sessionKey, rawData, signature)) {
            return "user check failed";
        }

        // 解密用户信息
        WxMaUserInfo userInfo = wxMaService.getUserService().getUserInfo(sessionKey, encryptedData, iv);
        Long usId = (Long) request.getAttribute("usId");
        UsInfo usInfo = usInfoService.getByIdForUpdate(usId);
        if (!CommUtil.checkNull(usInfo)){
            throw new ServiceException();
        }
        usInfo.setOpenId(userInfo.getOpenId()).setAvatar(userInfo.getAvatarUrl()).setNick(userInfo.getNickName());
        if (!usInfoService.updateById(usInfo)) {
            return ReturnBody.error(ResultCodeInfo.SERVICE_EXCEPTION);
        }
        return JSONObject.toJSONString(userInfo);
    }

    /**
     * <pre>
     * 获取用户绑定手机号信息
     * </pre>
     */
    @GetMapping("/phone")
    public String phone(@PathVariable String appid, String sessionKey, String signature,
                        String rawData, String encryptedData, String iv) {
        // 用户信息校验
        if (!wxMaService.getUserService().checkUserInfo(sessionKey, rawData, signature)) {
            return "user check failed";
        }
        // 解密
        WxMaPhoneNumberInfo phoneNoInfo = wxMaService.getUserService().getPhoneNoInfo(sessionKey, encryptedData, iv);

        return JSONObject.toJSONString(phoneNoInfo);
    }

}
